package com.example.myapplication; // 必须与MainActivity导入的包名一致

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private int count = 0;
    private boolean quit = false;
    private final MyServiceBinder myServiceBinder = new MyServiceBinder();

    public class MyServiceBinder extends Binder {
        public int getCount() {
            return count;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myServiceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 创建后台计数线程
        new Thread(() -> {
            while (!quit) {
                try {
                    Thread.sleep(1000);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        quit = true; // 停止计数线程
    }
}